package vn.com.vtv.weather;

import org.openweathermap.model.Cities;

import vn.com.vtv.R;
import vn.com.vtv.weather.adapter.CityAdapter;
import vn.hoasua.util.FileUtil;
import vn.hoasua.util.PlayServiceUtil;
import vn.hoasua.util.TimeUtil;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.text.util.Linkify;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.MediaController;
import android.widget.Spinner;
import android.widget.TextSwitcher;
import android.widget.TextView;
import android.widget.VideoView;
import android.widget.ViewSwitcher.ViewFactory;

import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.common.GooglePlayServicesRepairableException;

public class MainActivity extends Activity implements OnPreparedListener {
	private static Cities[] arrCities;
	private static CityAdapter cityAdapter;
	// publisher id: a153248e37b6647
	PlayServiceUtil ggService = new PlayServiceUtil();
	private AdView adView;
//	a153248e37b6647
//	3872f57b-31cf-4afd-9d81-7d250b5fb8c3
	private static final String AD_UNIT_ID = "ca-app-pub-3872f57b-31cf-4afd-9d81-7d250b5fb8c3";
		
	private Spinner spinnerTheme, spinnerCity;
	private ImageView imvBg;
	private VideoView videoView;
	private TextSwitcher videoTitle;
	private MediaController mc;

	Uri uri = Uri.parse("http://hanoisale.99s.vn/movie.mp4");
	String[] videoTitleArray = {"Chương trình dự báo thời tiết","Ngày hôm nay","Web: http://vtv.vn"};
	int messageCount = -1;
	// to keep current Index of text
	int currentIndex = -1;

	// handler update title video
	private Handler mHandler = new Handler();
	// Create a Runnable Instance
	Runnable r = new Runnable() {
		// Override the run Method
		public void run() {
			// TODO Auto-generated method stub
			try {
				// Update the TextSwitcher text
				if(videoTitleArray==null || videoTitleArray.length==0){
					 videoTitleArray = getResources().getStringArray(
								R.array.video_title_arrays);
				}
				messageCount = videoTitleArray.length;
				updateTextSwitcherText();

			} finally {
				mHandler.postDelayed(this, 5000);
			}
		}
	};
	
	

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		// Create an ad.
	    adView = new AdView(this);
	    adView.setAdSize(AdSize.BANNER);
	    adView.setAdUnitId(AD_UNIT_ID);
	    
	    LinearLayout layout = (LinearLayout) findViewById(R.id.lyAds);
	    layout.addView(adView);
	    
	    AdRequest adRequest = new AdRequest.Builder()
	        .addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
	        .addTestDevice("19C856C6E64C201E81F7E6D05E1DB17A")
	        .build();
	    
	    adView.loadAd(adRequest);
		
		spinnerTheme = (Spinner) findViewById(R.id.spinner_theme);
		spinnerCity = (Spinner) findViewById(R.id.spinner_city);
		imvBg = (ImageView) findViewById(R.id.imv_bg);
		videoView = (VideoView) findViewById(R.id.video);
		videoTitle = (TextSwitcher) findViewById(R.id.video_title);

		spinnerTheme.setOnItemSelectedListener(new CustomOnItemSelectedListener(
				spinnerTheme));
		spinnerCity.setOnItemSelectedListener(new CustomOnItemSelectedListener(
				spinnerCity));
		spinnerTheme.setSelection(VTVApplication.prefs.getInt(
				VTVApplication.KEY_BG_INDEX, 0));
		spinnerCity.setSelection(VTVApplication.prefs.getInt(
				VTVApplication.KEY_CITY_INDEX, 0));
		imvBg.setImageResource(VTVApplication.prefs.getInt(
				VTVApplication.KEY_BG_INDEX, 0) == 0 ? R.drawable.bg_00
				: R.drawable.bg_01);

		
		mc = new MediaController(this);
		mc.setAnchorView(videoView);
		mc.setMediaPlayer(videoView);
		videoView.setMediaController(mc);
		videoView.setOnPreparedListener(this);
		
		videoTitle.setFactory(new ViewFactory() {

			public View makeView() {
				// TODO Auto-generated method stub
				// create new textView and set the properties like clolr, size
				// etc
				TextView myText = new TextView(MainActivity.this);
				myText.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL);
				myText.setTextSize(14);
				myText.setSingleLine(true);
				myText.setTextColor(Color.BLUE);
				myText.setAutoLinkMask(Linkify.WEB_URLS);
				myText.setClickable(true);
				return myText;
			}
		});

//		if(uri!=null){
//			playVideo();
//		}
		videoTitleArray = getResources().getStringArray(R.array.video_title_arrays);
		refreshUI();
		
		// instruction for first run
		boolean isFirstRun = VTVApplication.prefs.getBoolean(VTVApplication.KEY_FIRST_RUN, true);
		if(isFirstRun){
			AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);
			alertDialog.setTitle("Dự báo thời tiết");
			alertDialog.setMessage("Hãy lựa chọn một thành phố.");
			alertDialog.setIcon(R.drawable.vtv_vn);
			alertDialog.setPositiveButton("Không hiện lại",
			        new DialogInterface.OnClickListener() {
			            public void onClick(DialogInterface dialog, int which) {
			            	VTVApplication.prefs.edit().putBoolean(VTVApplication.KEY_FIRST_RUN, false).commit();
			            	spinnerCity.performClick();
			            }
			        });
			// Showing Alert Dialog
			alertDialog.show();
		}
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		if (adView != null) {
	      adView.resume();
	    }
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				try {
					ggService.getIdThread(getApplicationContext());
				} catch (IllegalStateException e) {
					e.printStackTrace();
				} catch (GooglePlayServicesRepairableException e) {
					e.printStackTrace();
				}
			}
		}).start();
	}
	
	@Override
	public void onPause() {
		if (adView != null) {
			adView.pause();
		}
		super.onPause();
	}
	
	@Override
	public void onDestroy() {
		// Destroy the AdView.
		if (adView != null) {
			adView.destroy();
		}
		super.onDestroy();
	}
	
	private void refreshUI(){
		arrCities = FileUtil.getCitiesFromAssets(this);
		cityAdapter = new CityAdapter(this, arrCities);
		spinnerCity.setAdapter(cityAdapter);
		int lastPos = VTVApplication.prefs.getInt(VTVApplication.KEY_CITY_INDEX, 0);
		if(lastPos < arrCities.length-1)
			spinnerCity.setSelection(lastPos,true);
	}
	
	public void playVideo(){
		videoView.setVideoURI(uri);
		videoView.start();
		mHandler.postDelayed(r, 1000);
	}
	
	public void stopVideo(){
		videoView.stopPlayback();
		mHandler.removeCallbacks(r);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
//		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.action_settings:
			startActivity(new Intent(this, SettingActivity.class));
			break;
		default:
			break;
		}
		return super.onOptionsItemSelected(item);
		
	}

	// method to Update the TextSwitcher Text
	private void updateTextSwitcherText() {
		currentIndex++;
		if (currentIndex == messageCount)
			currentIndex = 0;
		String update = videoTitleArray[currentIndex];
		if(currentIndex==1){
			update = String.format(update, TimeUtil.getCurrentTimeFormat());
		}
		videoTitle.setText(update);
	}

	public class CustomOnItemSelectedListener implements OnItemSelectedListener {
		Spinner mSpinner;

		public CustomOnItemSelectedListener(Spinner mSpinner) {
			this.mSpinner = mSpinner;
		}

		public void onItemSelected(AdapterView<?> parent, View view, int pos,
				long id) {
			if (mSpinner.getId() == spinnerTheme.getId()) {
				switch (pos) {
				case 0:
					VTVApplication.prefs.edit()
							.putInt(VTVApplication.KEY_BGID, R.drawable.bg_00)
							.commit();
					break;
				case 1:
					VTVApplication.prefs.edit()
							.putInt(VTVApplication.KEY_BGID, R.drawable.bg_01)
							.commit();
					break;
				default:
					break;
				}
				VTVApplication.prefs.edit()
						.putInt(VTVApplication.KEY_BG_INDEX, pos).commit();
				imvBg.setImageResource(pos == 0 ? R.drawable.bg_00
						: R.drawable.bg_01);

			} else if (mSpinner.getId() == spinnerCity.getId()) {
				String cityName = arrCities[pos].name;
				Log.e("City Name", cityName);
				VTVApplication.prefs.edit()
						.putInt(VTVApplication.KEY_CITY_INDEX, pos).commit();
				VTVApplication.prefs.edit()
				.putInt(VTVApplication.KEY_CITY_ID, arrCities[pos].id).commit();
				VTVApplication.prefs.edit()
						.putString(VTVApplication.KEY_CITY, cityName).commit();
			}
			if (WidgetProvider._provider != null)
				WidgetProvider._provider.onUpdate(null, null, null);
			
			sendBroadcast(new Intent("android.appwidget.action.APPWIDGET_UPDATE"));
		}

		@Override
		public void onNothingSelected(AdapterView<?> arg0) {
		}

	}

	@Override
	public void onPrepared(MediaPlayer mp) {
		
		mp.setOnBufferingUpdateListener(new OnBufferingUpdateListener() {
			
			@Override
			public void onBufferingUpdate(MediaPlayer mp, int percent) {
				TextView buffer = (TextView)findViewById(R.id.tv_buffer_video);
				if(percent<98){
					buffer.setVisibility(View.VISIBLE);
					findViewById(R.id.prg_video).setVisibility(View.VISIBLE);
					buffer.setText("Buffering.. "+percent+"%");
				}else{
					buffer.setVisibility(View.GONE);
					findViewById(R.id.prg_video).setVisibility(View.GONE);
					buffer.setText("Loading...");
				}
			}
		});
	}
}
